package kr.hkit.android_bookmgr.activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.DTO.BookData;
import kr.hkit.android_bookmgr.adapter.SearchAdapter;
import kr.hkit.android_bookmgr.parser.SearchParser;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddBookSearchActivity extends Activity { //네이버 api
	private MenuItem mSearch;
	private String key="0c40f676bf69bfc38b1a9d508676c9ca";
	private ProgressDialog dialog;
	
	private ListView myList;
	private SearchParser Nparser;
	private SearchAdapter searchAdapter;
	
	private ArrayList<BookData> data;
	private String qry;
	
	final int count=20;
	int start=1;
	private ImageView image;
	
	private LinearLayout startlinear, endlinear;
	private EditText startdate, enddate;
	private int mYear, mMonth, mDay;
	private View datepicker;
	
	private int pos;
	private BookDAO mBookMgr;
	private SearchView sv;
	
	
	

    
    @Override 
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
		setContentView(R.layout.addbook_search_activity);
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);

		calendar();
		mBookMgr = BookDAO.getInstance(this);

		Nparser = new SearchParser(key);
		myList = (ListView) findViewById(R.id.addbook_search_linearview);
		myList.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					 int position, long id) {
				//검색내용 리스트뷰에서 대화상자띄우기
				final RelativeLayout rel = (RelativeLayout) View.inflate(AddBookSearchActivity.this, R.layout.addbook_search_dialog, null);
				
				final EditText name = (EditText)rel.findViewById(R.id.addbook_searchDia_name);
				final EditText author = (EditText)rel.findViewById(R.id.addbook_searchDia_author);
				final EditText publisher = (EditText)rel.findViewById(R.id.addbook_searchDia_publisher);
				final EditText totalpage = (EditText)rel.findViewById(R.id.addbook_searchDia_totalpage);
				TextView description = (TextView) rel.findViewById(R.id.addbook_searchDia_description);
				image = (ImageView) rel.findViewById(R.id.addbook_searchDia_img);
				
				startlinear = (LinearLayout) rel.findViewById(R.id.addbook_searchDia_startdatelinear); //독서시작일 리니어
				endlinear = (LinearLayout) rel.findViewById(R.id.addbook_searchDia_enddatelinear); //독서완료일 리니어
				startdate = (EditText) rel.findViewById(R.id.addbook_searchDia_startdateedit);//독서시작일 에딧텍스트
				startdate.setOnFocusChangeListener(mOnFocusChangeListener);
				enddate = (EditText) rel.findViewById(R.id.addbook_searchDia_enddateedit);//독서완료일에딧텍스트
				enddate.setOnFocusChangeListener(mOnFocusChangeListener);
				
				Spinner spin = (Spinner) rel.findViewById(R.id.addbook_searchDia_status);//상태 스피너
				ArrayAdapter<CharSequence> adspin = ArrayAdapter.createFromResource(AddBookSearchActivity.this, 
							R.array.addbook_direct_statuslist, android.R.layout.simple_spinner_dropdown_item);
				spin.setAdapter(adspin);
					
					spin.setOnItemSelectedListener(new OnItemSelectedListener() {
						//스피너 - 상태부분
						@Override
						public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {
							pos = position;
							if(position==2){ //읽는 중 
								startlinear.setVisibility(LinearLayout.VISIBLE);
								endlinear.setVisibility(LinearLayout.GONE);
								enddate.setText("");
							}else if(position==3){ //읽기 완료
								startlinear.setVisibility(LinearLayout.VISIBLE);
								endlinear.setVisibility(LinearLayout.VISIBLE);
							}else{ //없음, 읽을예정은 필요없으니까 invisible
								startlinear.setVisibility(LinearLayout.GONE);
								endlinear.setVisibility(LinearLayout.GONE);
								startdate.setText("");
								enddate.setText("");
							}
						}//spinner

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
						}
					});//spin.setOnItemSelectedListener
					
					
				//이미지 
				final String str = data.get(position).bookimg;
				ImageUtil.imageLoader(AddBookSearchActivity.this);
				DisplayImageOptions options = ImageUtil.dispalyOptions();
				ImageLoader.getInstance().displayImage(str, image, options); //http주소만 출력할거니까 
				
				String mName = data.get(position).name; //여기도 b태그
				String resultName = removeB(mName);
				name.setText(resultName); 
				String mDescription = data.get(position).description;
				String resultDesc = removeB(mDescription);
				description.setText(resultDesc); 
				String mAuthor = data.get(position).author;
				String resultAuthor = removeB(mAuthor);
				author.setText(resultAuthor);
				String mPublisher = data.get(position).publisher;
				String resultPublisher = removeB(mPublisher);
				publisher.setText(resultPublisher);
				
				new AlertDialog.Builder(AddBookSearchActivity.this)
				.setView(rel)
				.setPositiveButton("확인", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) { //등록버튼 클릭시 -> DB인서트
						//DB등록!!!!
						ContentValues addRowValue = new ContentValues();
						addRowValue.put("name", name.getText().toString().trim());
						addRowValue.put("author", author.getText().toString().trim());
						addRowValue.put("publisher", publisher.getText().toString().trim());
						addRowValue.put("totalpage", totalpage.getText().toString().trim());
						if(pos==3){
							addRowValue.put("currentpage", totalpage.getText().toString().trim());
						}
						addRowValue.put("status",pos);
						addRowValue.put("bookimg", str); //이미지 주소
						addRowValue.put("imgtype", 2); //2이면 검색 
						addRowValue.put("startdate", startdate.getText().toString().trim());
						addRowValue.put("enddate", enddate.getText().toString().trim());				
						mBookMgr.insertBook(addRowValue);
						
						Toast.makeText(AddBookSearchActivity.this, "등록되었습니다.", Toast.LENGTH_SHORT).show();
						
						finish();
					}
				})
				.setNegativeButton("취소", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						Toast.makeText(AddBookSearchActivity.this,"취소하였습니다.", Toast.LENGTH_SHORT).show();
					}
				})
				.show();
			}//onItemClick
		});
		
    }//onCreate
    
    
    private final Handler handler=new Handler(){
    	public void handleMessage(final Message msg){
    		dialog.dismiss();
    		
    		searchAdapter=new SearchAdapter(AddBookSearchActivity.this,R.layout.addbook_search_row, data); //adapter 생성
    		myList.setAdapter(searchAdapter);
    		
    	}
    };
 
    
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
		switch (item.getItemId()) {
			case android.R.id.home:
				  Intent intent = new Intent(this, BookListActivity.class); 
				  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //액티비티 쌓이지 않기위해. 바로메인
				  startActivity(intent);
				  break;
		}
		return super.onOptionsItemSelected(item);

	}; //홈으로 이동
    
    
	private void calendar(){
		
		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		
	}
    
    
    @Override
	protected void onPause() {
		super.onPause();
		mBookMgr.close();
	}
    
    @Override
    	public boolean onCreateOptionsMenu(Menu menu) {
    	
    	MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.addbook_search_actionbar, menu);
		mSearch = menu.findItem(R.id.addbook_search_actionbar);

		sv = (SearchView) mSearch.getActionView();
		sv.setIconified(false);
		sv.setQueryHint("도서명을 입력해주세요.");
		sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

			@Override
			public boolean onQueryTextSubmit(String query) {
				qry = query.trim();
				getNewList(qry,count,start);
				sv.setIconified(true);
				return true;
			}

			@Override
			public boolean onQueryTextChange(String newText) {
				return true;
			}
		});

		return super.onCreateOptionsMenu(menu);
    	
    	}//onCreateOptionsMenu
    
    
    public void getNewList(final String qry,final int count,final int starts){
		dialog=ProgressDialog.show(this, "Loading..", "도서리스트를 불러옵니다",true,false);
		new Thread(){
			public void run(){
				data = Nparser.getBookData(qry, count,starts); // 네이버 api를 이용해 정보를 얻어옴
				handler.sendEmptyMessage(0);
			}
		}.start();
	}//getNewList
    
    
    //독서시작일 독서완료일 textview 포커스 datepicker
    OnFocusChangeListener mOnFocusChangeListener = new OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			datepicker = v;
			if(hasFocus)
				new DatePickerDialog(AddBookSearchActivity.this, mDateSetListener, mYear, mMonth, mDay).show();
		}
	};
	
    
    DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			
			if(datepicker.getId()==R.id.addbook_searchDia_startdateedit){
				startdate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
			}else {
				enddate.setText(String.format("%d/%02d/%d", mYear, mMonth+1, mDay));
			}
		}
	};//DatePickerDialog
	
    
	 public void mOnClick(View v){
	    	switch(v.getId()){
	    	case R.id.prepage:
	    		sv.setIconified(true);
	    		if(start <= 20){
					Toast.makeText(this, "이전 페이지가 없습니다", Toast.LENGTH_SHORT).show();
	    		}else{
					start-=20;
					getNewList(qry,count,start);
				}
				break;
	    	case R.id.nextpage: 
	    		sv.setIconified(true);
	    		Log.d("start", start+"");
	    		start+=20;
				getNewList(qry,count,start);
				break;
	    	}
	    }
    
	
	private String removeB(String b_name){ //b태그 제거
		Log.d("b_name", b_name);
		
		StringTokenizer stk = new StringTokenizer(b_name,"</b>");
		String remove ="";
		for(int i=0; stk.hasMoreTokens(); i++){
			 remove += stk.nextToken();
		}
		return remove;
	} 
	
	/*class ImageLoadingTask extends AsyncTask<String, Void, Bitmap> {
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Bitmap doInBackground(String... strs) {
			URL url = null;
			BufferedInputStream bis = null;
			Bitmap bitmap = null;

			try {
				url = new URL(strs[0]);
				HttpURLConnection con = (HttpURLConnection) url.openConnection();
				bis = new BufferedInputStream(con.getInputStream());
				bitmap = BitmapFactory.decodeStream(bis);
				bis.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			image.setImageBitmap(result);
		}
	}// ImageLoadingTask
*/
	
}//end of class
